/**
 * This file is part of AppStoreBot.
 *
 *  AppStoreBot is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AppStoreBot is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AppStoreBot.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package lu.pragmaconsult.appstorebot.itunes;


import static lu.pragmaconsult.appstorebot.itunes.Constants.ATT_HREF;
import static lu.pragmaconsult.appstorebot.itunes.Constants.AUTHENTICATION_URL;
import static lu.pragmaconsult.appstorebot.itunes.Constants.SALES_AND_TREND;
import static lu.pragmaconsult.appstorebot.itunes.Constants.XPATH_A;

import javax.xml.xpath.XPathConstants;

import lu.pragmaconsult.appstorebot.BotContext;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * TODO: Type comment
 * 
 * @author Wilfried Vandenberghe (wilfried.vandenberghe at pragmaconsult.lu)
 */
class AuthenticationBotState extends AbstractBotState {

	private static final Logger logger = LoggerFactory.getLogger(AuthenticationBotState.class);

	/* (non-Javadoc)
	 * @see lu.pragmaconsult.appstorebot.itunes.AbstractBotState#createHttpMethod(lu.pragmaconsult.appstorebot.BotContext, org.apache.commons.httpclient.HttpClient)
	 */
	@Override
	protected HttpMethod createHttpMethod(BotContext context, HttpClient httpClient) {
		if(logger.isDebugEnabled()) {
			logger.debug("Signing into iTunes Connect web site");
		}
		
		PostMethod post = new PostMethod(context.getContextAttribute(AUTHENTICATION_URL));

		// Prepare login parameters
		NameValuePair accountName = new NameValuePair("theAccountName", context.getAppleId());
		NameValuePair accountPW = new NameValuePair("theAccountPW", context.getPassword());
		NameValuePair continuex = new NameValuePair("1.Continue", "0");
		post.setRequestBody(new NameValuePair[] { accountName, accountPW, continuex });

		return post;
	}

	/* (non-Javadoc)
	 * @see lu.pragmaconsult.appstorebot.itunes.AbstractBotState#getNextState()
	 */
	@Override
	protected BotState getNextState() {
		return new SalesAndTrendBotState();
	}

	/* (non-Javadoc)
	 * @see lu.pragmaconsult.appstorebot.itunes.AbstractBotState#processResponseBody(lu.pragmaconsult.appstorebot.BotContext, java.io.InputStream)
	 */
	@Override
	protected void processResponseBody(BotContext context, HttpMethod method) {
		try {
			HtmlParser parser = new HtmlParser(method.getResponseBodyAsStream());

			NodeList nodes = (NodeList) parser.evaluate(XPATH_A, XPathConstants.NODESET);
			if (nodes == null) {
				throw new Exception("Cannot found sales and trend post url");
			}

			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);
				String ref = node.getAttributes().getNamedItem(ATT_HREF).getNodeValue();
				if (ref.contains("/WebObjects/iTunesConnect.woa/wo/") && ref.contains(".0.9.7.2.9.1.0.0.3")) {
					context.setContextAttribute(SALES_AND_TREND, ref);
					return;
				}
			}
		} catch (Exception e) {
			logger.error("Error while getting action url", e);
			throw new IllegalStateException(e);
		}

		throw new IllegalStateException(
				"Error while getting sales and trend url.");

	}

}
